<template>
  <div>
    <a-card>
      <title-name v-if="isEdit == 'add'" title="新增设计变更" />
      <title-name v-if="isEdit == 'edit'" title="编辑设计变更" />
      <title-name v-if="isEdit == 'view' || type == 'approve'" title="查看设计变更" />
      <a-form-model ref="form1" layout="horizontal" :model="form" :rules="rules">
        <a-row :gutter="24">
          <a-col :md="16" :sm="16">
            <!--              designTypeNames: ["a1类", "a2类", "a3类"]-->
            <a-form-model-item label="所属单位" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"
              :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }" prop="projectId">
              <org-tree-select v-model="form.projectId" is-auto-select-first is-need-auth is-special-tree
                :is-query-projec-detail="true" :extra-query="{
                  designTypeNames: ['a1类']
                }" :disabled="isEdit == 'view' || type == 'approve' || resolveInfo" check-strictly @select="selectOrg"
                @getProjectInfo="getProjectInfo" />
            </a-form-model-item>
          </a-col>
          <!--          <a-col-->
          <!--            :md="8"-->
          <!--            :sm="8"-->
          <!--          >-->
          <!--            <a-form-model-item-->
          <!--              label="分公司"-->
          <!--              :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"-->
          <!--              :disabled="isEdit == 'view'"-->
          <!--              :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }"-->
          <!--              prop="branchId"-->
          <!--            >-->
          <!--              <SelectSubCompany-->
          <!--                v-model="form.branchId"-->
          <!--                :disabled="isEdit == 'view' || type == 'approve'"-->
          <!--                placeholder="请选择"-->
          <!--                @change="getProjectNames"-->
          <!--              />-->
          <!--            </a-form-model-item>-->
          <!--          </a-col>-->
          <!--          <a-col-->
          <!--            :md="8"-->
          <!--            :sm="8"-->
          <!--          >-->
          <!--            <a-form-model-item-->
          <!--              label="项目名称"-->
          <!--              :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"-->
          <!--              :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }"-->
          <!--              prop="projectId"-->
          <!--            >-->
          <!--              <SelectProject-->
          <!--                v-model="form.projectId"-->
          <!--                placeholder="请选择"-->
          <!--                :disabled="isEdit == 'view' || type == 'approve'"-->
          <!--                :form="form"-->
          <!--                :is-clear="true"-->
          <!--                :if-design-change="true"-->
          <!--                key-value="branchId"-->
          <!--                @change="getPojectDetails(form.projectId)"-->
          <!--                @projectDeptId="projectDeptmentId"-->
          <!--              />-->
          <!--            </a-form-model-item>-->
          <!--          </a-col>-->
          <a-col :md="8" :sm="8">
            <a-form-model-item label="项目设计管理类别" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"
              :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }">
              <BaseInput v-model="form.projectType" placeholder="" disabled />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :md="8" :sm="8">
            <a-form-model-item label="工程类别" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"
              :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }" prop="constructionTypeId">
              <SelectProjectType :init="false" :disabled="isEdit == 'view' || type == 'approve' || resolveInfo" @change="changeSelectProjectType" v-model="form.constructionTypeId" :defaultCheck="addtable" :id="form.projectId"></SelectProjectType>
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8">
            <a-form-model-item label="专业类型" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"
              :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }" prop="professionalTypeId">
              <!-- 因为数据有时候被删除匹配不上，所用name -->
              <a-input disabled v-if="isEdit == 'view' || type == 'approve' || resolveInfo"  v-model="form.professionalTypeName"></a-input>
              <a-tree-select v-else  @change="changeProfessional"   v-model="form.professionalTypeId"  :replaceFields="{children:'children', title:'majorName', key:'id', value: 'id' }" :showSearch="true" :tree-data="listP" :disabled="isEdit == 'view' || type == 'approve'">
                <a-spin v-if="professionalFetching" slot="notFoundContent" size="small" />
                <a-icon  v-if="professionalFetching" style="color: #096dd9" slot="suffixIcon" type="loading" />
              </a-tree-select>
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8">
            <a-form-model-item label="设计变更名称" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"
              :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }" prop="changeName">
              <BaseInput v-model="form.changeName" placeholder="请输入" :max-length="30"
                :disabled="isEdit == 'view' || type == 'approve' || resolveInfo" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :md="8" :sm="8">
            <a-form-model-item label="设计变更编号" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"
              :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }" prop="changeNum">
              <BaseInput v-model="form.changeNum" placeholder="请输入" :max-length="30"
                :disabled="isEdit == 'view' || type == 'approve' || resolveInfo" />
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8">
            <a-form-model-item label="专业" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"
              :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }" prop="major">
              <a-select v-model="form.major" :disabled="isEdit == 'view' || type == 'approve' || resolveInfo" placeholder="请选择">
                <a-select-option v-for="item in profession" :key="item.id" :value="item.id">
                  {{
                      item.name
                  }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8">
            <a-form-model-item label="发起部门" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"
              :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }" prop="department">
              <a-select v-model="form.department" placeholder="请选择" :disabled="isEdit == 'view' || type == 'approve' || resolveInfo">
                <a-select-option value="设计技术部">
                  设计技术部
                </a-select-option>
                <a-select-option value="设计质量部">
                  设计质量部
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8">
            <a-form-model-item label="施工图设计单位" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"
              :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }" prop="designUnitName">
              <BaseInput v-model="form.designUnitName" :max-length="30" placeholder="选择或输入施工图设计单位"
                :disabled="isEdit == 'view' || type == 'approve' || resolveInfo" />
            </a-form-model-item>
          </a-col>
          <a-button v-if="isEdit == 'add' || isEdit == 'edit'" type="primary" @click="changeData">
            选择
          </a-button><span v-if="isEdit == 'add' || isEdit == 'edit'">（从设计资源库中选择）</span>
        </a-row>
        <a-row :gutter="24">
          <a-col :md="8" :sm="8">
            <a-form-model-item label="施工图版本编号" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"
              :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }" prop="versionNum">
              <BaseInput v-model="form.versionNum" placeholder="请输入施工图版本编号" :max-length="30"
                :disabled="isEdit == 'view' || type == 'approve' || resolveInfo" />
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8">
            <a-form-model-item label="变更日期" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"
              :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }" prop="changeTime">
              <a-date-picker v-model="form.changeTime" style="width: 100%"
                :disabled="isEdit == 'view' || type == 'approve'|| resolveInfo" placeholder="请选择日期" @change="onChangeTime" />
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8">
            <a-form-model-item label="变更形式" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"
              :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }" prop="changeForm">
              <a-select v-model="form.changeForm" placeholder="请选择" :disabled="isEdit == 'view' || type == 'approve' || resolveInfo">
                <a-select-option v-for="item in changeForm" :key="item.id" :value="item.id">
                  {{
                      item.name
                  }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :md="8" :sm="8">
            <a-form-model-item label="预期影响天数(天)" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"
              :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }" prop="influences">
              <BaseInputNumber v-model="form.influences" :min="0" :max="999999999999" placeholder="请输入"
                :disabled="isEdit == 'view' || type == 'approve' || resolveInfo" />
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8">
            <a-form-model-item label="成本费用(万)" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"
              :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }" prop="cost" help="备注：正数表示增加，负数表示减少">
              <BaseInputNumber v-model="form.cost" placeholder="输入成本费用" :max="999999999999"
                :disabled="isEdit == 'view' || type == 'approve' || resolveInfo" />
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8">
            <a-form-model-item label="变更费用(万)" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"
              :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }" prop="changeCost" help="备注：正数表示增加，负数表示减少">
              <BaseInputNumber v-model="form.changeCost" :max="999999999999" placeholder="输入变更费用"
                :disabled="isEdit == 'view' || type == 'approve' || resolveInfo" @change="calcChangeLevel" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :md="8" :sm="8">
            <a-form-model-item label="单项工程设计变更率(%)" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"
              :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }">
              <BaseInput v-model="form.changeRate" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8">
            <a-form-model-item label="设计变更等级" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"
              :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }">
              <BaseInput v-model="form.changeLevel" disabled />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :md="8" :sm="8">
            <a-form-model-item label="创建人" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"
              :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }">
              <BaseInput v-model="form.creater" placeholder="" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8">
            <a-form-model-item label="创建时间" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"
              :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }">
              <BaseInput v-model="currentDate" disabled />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :md="8" :sm="8">
            <a-form-model-item label="变更原因" :label-col="{ lg: { span: 2 }, sm: { span: 2 } }"
              :wrapper-col="{ lg: { span: 22 }, sm: { span: 22 } }" prop="changeReason">
              <!--<a-tree-select-->
              <!--:disabled="isEdit == 'view' || type == 'approve'"-->
              <!--v-model="form.changeType"-->
              <!--style="width: 100%"-->
              <!--:tree-data="changeType"-->
              <!--multiple-->
              <!--/>-->
              <a-select v-model="form.changeReason" placeholder="请选择" :disabled="isEdit == 'view' || type == 'approve'|| resolveInfo"
                @change="getChangeType">
                <a-select-option v-for="item in changeReasons" :key="item.value" :value="item.value">
                  {{ item.title }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :md="16" :sm="16">
            <a-form-model-item readonly label="变更类型" :label-col="{ lg: { span: 2 }, sm: { span: 2 } }"
              :wrapper-col="{ lg: { span: 22 }, sm: { span: 22 } }" prop="changeType">
              <a-tree-select id="a-tree-select" v-model="form.changeType" placeholder="多选"
                :disabled="isEdit == 'view' || type == 'approve' || resolveInfo" style="width: 100%" :tree-data="changeType"
                multiple />
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-row :gutter="24">
          <a-col :md="24" :sm="24">
            <a-form-model-item label="设计变更及内容" :label-col="{ lg: { span: 2 }, sm: { span: 2 } }"
              :wrapper-col="{ lg: { span: 22 }, sm: { span: 22 } }" prop="contents">
              <BaseTextarea v-model="form.contents" placeholder="请输入设计变更及内容" type="textarea"
                :disabled="isEdit == 'view' || type == 'approve' || resolveInfo" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :md="24" :sm="24">
            <a-form-model-item label="工程总承包项目部会议评审意见" :label-col="{ lg: { span: 3 }, sm: { span: 3 } }"
              :wrapper-col="{ lg: { span: 21 }, sm: { span: 21 } }" prop="opinion">
              <BaseTextarea v-model="form.opinion" placeholder="请输入工程总承包项目部会议评审意见" type="textarea"
                :disabled="isEdit == 'view' || type == 'approve' || resolveInfo" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>

      <a-modal v-model="visible" width="900px" :title="title">
        <template slot="footer">
          <a-button key="back" @click="handleCancel">
            取消
          </a-button>
          <a-button type="primary" @click="handleOk">
            确定选择
          </a-button>
        </template>
        <searchData :search-data="searchArr" @search="searchDatas" />

        <a-table bordered :pagination="false"
          :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange, type: 'radio' }"
          :columns="columns" :data-source="tableData" row-key="id">
          <span slot="serial" slot-scope="text, record, index">{{ index + 1 }}</span>
        </a-table>
        <pagination v-model="pageNo" :total="totalSize" :page-size.sync="pageSize" @change="handlePageChange"
          @showSizeChange="showSizeChange" />
      </a-modal>
    </a-card>

    <a-card v-if="showRecord == 1">
      <title-name title="设计变更记录" />
      <a-form-model ref="form1" layout="horizontal">
        <a-row :gutter="24">
          <a-col :md="8" :sm="8">
            <a-form-model-item label="记录类型" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"
              :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }" prop="recordType">
              <a-select v-model="form.recordType" disabled>
                <a-select-option value="0">
                  变更终止
                </a-select-option>
                <a-select-option value="1">
                  变更完成维护
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8">
            <a-form-model-item label="记录人" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"
              :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }">
              <BaseInput v-model="form.recorder" placeholder="" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8">
            <a-form-model-item label="记录时间" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"
              :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }">
              <BaseInput v-model="form.recordTime" placeholder="" disabled />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :md="24" :sm="24">
            <a-form-model-item label="备注说明" :label-col="{ lg: { span: 7 }, sm: { span: 7 } }"
              :wrapper-col="{ lg: { span: 17 }, sm: { span: 17 } }" prop="remark">
              <BaseTextarea v-model="form.remark" disabled />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
      <title-name title="相关附件信息" />
      <a-table row-key="id" bordered :columns="columnAssment" :data-source="form.uploadFileList">
        <span slot="serial" slot-scope="text, record, index">{{ index + 1 }}</span><span slot="action"
          slot-scope="text, record, index">
          <a :href="'/api/ycloud-file-center/oper/download?access_token=' + token + '&fileId=' + record.fileId"
            target="_parent">导出</a>
          <a-divider type="vertical" />
          <a href="javascript:" @click="$filePreview(record)">预览</a>
        </span>
      </a-table>
    </a-card>
    <a-card :bordered="false" v-if="isEdit == 'view' && todoList.length && !resolveInfo && !soleId">
        <title-name title="岗位接收信息"></title-name>
        <a-table  :columns="postColumns" :data-source="todoList" bordered :pagination="false"></a-table>
      </a-card>
    <div class="page-btn-right-top">
      <a-button v-if="isEdit == 'add' || isEdit == 'edit'" :loading="draftLoading" type="primary"
        style="margin-right: 20px" @click="saveDraft">
        保存草稿
      </a-button>
      <a-button v-if="isEdit == 'add' || isEdit == 'edit'" :loading="loading" type="primary" style="margin-right: 20px"
        @click="submit">
        提交
      </a-button>
      <a-button v-if="soleId && !resolveInfo"
          class="button_right"
          type="primary"
          @click="handleTodo"
          style="margin-right: 20px"
          >确认接收</a-button>
      <a-button type="primary" @click="goBack">
        关闭
      </a-button>
    </div>
    <selectApprover :business-id="businessId" :process-config="setProcessConfig" />
  </div>
</template>

<script>
import { getTypes, getLabelTypes } from '@/api/commons'
import { getDesignResourcesList } from '@/api/design/parameter'
import {
  addDesignChange,
  getDesignDetails,
  getDesignChangeLabels,
  getProjectBranchType,
  editDesignChange,
  getChangeReasons,
  getChangeTypes,
  drawChangeUpdateSoleA
} from '@/api/project/designChange'
import { getUserBranch, getUserProject, getProjectsDel } from '@/api/project/projects'
import { getTypeTrees } from '@/api/commons'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/SelectProjects/SelectProject' // 项目
import ARow from 'ant-design-vue/es/grid/Row'
import { getProject } from '@/api/themeChoose/themeChoose'
import { getDept } from '@/api/commons'
import SelectProjectType from '@/components/Select/SelectProjectType' // 工程类别
import { majorTypeSelectListTree } from '@/api/technology'
import { finishBusinessTodo } from '@/api/commons.js'
import moment from 'moment';
import Vue from 'vue'

const columns = [
  {
    title: '序号',
    width: 65,
    dataIndex: 'serial',

    scopedSlots: { customRender: 'serial' },
  },
  {
    title: '设计资源名称',
    dataIndex: 'name',
    width: '20%',
  },
  {
    title: '设计资源类型',
    dataIndex: 'resTypeName',
    width: '30%',
  },
  {
    title: '设计资源等级',
    dataIndex: 'resLevelName',
    width: '30%',
  },
]
const columnAssment = [
  {
    title: '序号',
    width: 65,
    dataIndex: 'serial',

    scopedSlots: { customRender: 'serial' },
  },
  {
    title: '附件名称',
    dataIndex: 'fileName',
  },
  {
    title: '附件格式',
    dataIndex: 'suffixName',
    width: '25%',
  },
  {
    title: '操作',
    key: 'action',
    width: '20%',
    scopedSlots: { customRender: 'action' },
  },
];
const postColumns = [
{
    title: '序号',
    width: 80,
    dataIndex: 'index',
    customRender() {
      return arguments[2] + 1
    }
  },
  {
    title: '岗位名称',
    dataIndex: 'workName'
  },
  {
    title: '接收状态',
    dataIndex: 'acceptStatus'
  },
  {
    title: '接收人',
    dataIndex: 'personName'
  },
  {
    title: '接收时间',
    dataIndex: 'acceptTime',
    customRender(text) {
      return text && moment(text).format('YYYY-MM-DD')
    }
  },
]
export default {
  name: 'a' + Date.now(),
  components: {
    ARow,
    SelectSubCompany,
    SelectProject,
    SelectProjectType
  },
  props: {
        isAudit: {
            // 是否作为审批详情
            type: Boolean,
            default: false
        }
    },
  data() {
    return {
      showRecord: 0,
      token: '',
      columnAssment, // 变更记录的文件列
      draftLoading: false, // 保存草稿按钮loading
      changeReasons: [],
      columns,
      loading: false,
      pageNo: 1,
      pageSize: 10,
      totalSize: 0,
      disabled: false,
      postColumns,
      type: '',
      searchArr: [
        // 搜索框
        {
          name: '设计资源名称',
          value: 'designResourceName',
          type: 'input',
        },
        {
          name: '设计资源类型',
          value: 'resTypeId',
          type: 'select',
          data: [],
        },
        {
          name: '设计资源等级',
          value: 'resLevelId',
          type: 'select',
          data: [],
        },
      ],
      tableData: [], // 设计资源台账

      changeForm: [], // 变更形式
      changeReason: [], // 变更原因
      changeType: [], // 变更类型
      profession: [], // 专业
      proposer: [], // 提出方
      projectIds: [], // 提出方

      projects: [], // 分公司下的项目

      value: [],
      value2: [],

      queryParam: {},
      loadData: (parameter) => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        return getDesignResourcesList(requestParameters).then((res) => {
          return res
        })
      },

      visible: false,
      title: '选择设计资源',
      todoList:[],

      form: {
        designUnitId: null,
        designUnitName: null,
        changeRate: null, // 设计变更率
        changeLevel: null, // 变更等级
        projectType: null,
        changeType: null,
        creater: JSON.parse(sessionStorage.getItem('ycloud-user_info')).name,
      },

      currentDate: '', // 当前日期

      isEdit: '',
      id: '',
      projectNames: [],
      fetching: false,
      professionalFetching:false,

      selectedRowKeys: [],
      selectRow: {},

      contractAmount: '', // 自有施工合同额
      deptList: [], // 项目部下所有部门

      projectDeptId: '', //项目下的部门
      rules: {
        branchId: [{ required: true, message: '请选择分公司', trigger: 'blur' }],
        projectId: [{ required: true, message: '请选择项目', trigger: 'blur' }],
        changeName: [{ required: true, message: '请输入设计变更名称', trigger: 'blur' }],
        changeNum: [{ required: true, message: '请输入设计变更编号', trigger: 'blur' }],
        major: [{ required: true, message: '请选择专业', trigger: 'blur' }],
        department: [{ required: true, message: '请选择发起部门', trigger: 'blur' }],
        designUnitName: [{ required: true, message: '请输入施工图设计图单位', trigger: 'change' }],
        versionNum: [{ required: true, message: '请输入施工图版本编号', trigger: 'blur' }],
        changeTime: [{ required: true, message: '请选择变更日期', trigger: 'change' }],
        changeForm: [{ required: true, message: '请选择变更形式', trigger: 'blur' }],
        influences: [{ required: true, message: '请输入预期影响天数', trigger: 'blur' }],
        proposer: [{ required: true, message: '请选择提出方', trigger: 'blur' }],
        cost: [{ required: true, message: '请输入成本费用', trigger: 'blur' }],
        changeCost: [{ required: true, message: '请输入变更费用', trigger: 'blur' }],
        changeType: [{ required: true, message: '请选择变更类型', trigger: 'change' }],
        changeReason: [{ required: true, message: '请输入变更原因', trigger: 'change' }],
        contents: [{ required: true, message: '请输入变更及内容', trigger: 'blur' }],
        opinion: [{ required: true, message: '请输入工程总承包项目部会议评审意见', trigger: 'blur' }],
        professionalTypeId: [{ required: true, message: '请选择' }],
        constructionTypeId: [{ required: true, message: '请选择' }],
      },
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null,
      listP:[],
      majorTypeSelectListTreeData:[],
      soleId:this.$route.query.soleId,
      resolveInfo:this.$route.query.resolveInfo
    }
  },
  watch: {
    isAudit: {
        immediate: true,
        handler(val) {
            if (val) {
                this.$nextTick(() => {
                  this.isEdit = 'view';
                  this.id = this.$route.query.businessId;
                  this.getDesignDetails()
                })
            }
        }
    }
    },
  async created() {
    this.majorTypeSelectListTree();
    this.token = Vue.getAcloudProvider().getAccessToken()
    this.id = this.$route.query.id
    this.isEdit = this.$route.query.isEdit
    this.type = this.$route.query.type
    if (this.isEdit == 'edit' || this.isEdit == 'view' || this.type == 'approve') {
      this.getDesignDetails()
    }
    this.showRecord = this.$route.query.showRecord
    this.getChangeReason()
    this.getCurrentDate() // 获取当前日期
    this.getTypes() // 获取设计资源类型标签
    this.getDesignResourcesList()
    this.getDesignChangeLabels()
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('design_change_manage')
  },
  mounted() {
    // 设置变更类型输入框readonly
    let treeDelectDom = document.querySelector('#a-tree-select')
    if (treeDelectDom) {
      let inputDom = treeDelectDom.querySelector('input')
      if (inputDom) {
        inputDom.readOnly = true
      }
    }
  },
  computed:{
    addtable() {
        return this.$route.query.isEdit == 'add';
      },
  },
  methods: {
    //处理待办
    handleTodo(){
      let that = this;
      let obj = {
        id:this.id,
        soleId:this.soleId
      }
      this.$confirm({
        title: `你确认接收吗？`,
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          that.loading = true;
          drawChangeUpdateSoleA(obj).then((res)=>{
             if(res?.data?.code == 200){
              finishBusinessTodo({ id: that.$route.query.messageId }).then((res1) => {
                that.loading = false;
                if (res1.code !== '0') {
                  return
                }
              })
              that.$message.success('确认接收成功');
              that.$multiTab.close()
             }
          })
        },
        onCancel() {
          
        },
      })
    },
    changeSelectProjectType(val){
      this.filtraType(val);
      this.$set(this.form, 'professionalTypeName', '')
      this.$set(this.form, 'professionalTypeId', null)
    },
    changeProfessional(e,obj){
      console.log(e,obj)
      this.$set(this.form,'professionalTypeName', obj[0])
    },
    majorTypeSelectListTree() {
      this.professionalFetching = true;
      majorTypeSelectListTree(this.form.projectId).then(res=>{
        res?.data.forEach(item=>{
          item.majorName = item.programmeName
          item.disabled = true
        })
        this.majorTypeSelectListTreeData = res.data;
        this.form.constructionTypeId && this.filtraType(this.form.constructionTypeId);
        this.professionalFetching = false;
      })
    },
    filtraType(val){
      let findData = this.majorTypeSelectListTreeData && this.majorTypeSelectListTreeData.find((item)=>item.id == val);
      this.listP = [findData] || []
    },
    selectOrg(val) {
      if (val.length > 1) {
        this.form.branchId = val[val.length - 2].orgId
        this.getPojectDetails(this.form.projectId)
      }
    },
    getProjectInfo(info) {
      this.projectDeptId = info.projectDeptOrgId
    },
    handlePageChange(pageNo, pageSize) {
      this.pageNo = pageNo
      this.getDesignResourcesList()
    },
    showSizeChange(pageNo, pageSize) {
      this.pageNo = 1
      this.pageSize = pageSize
      this.getDesignResourcesList()
    },
    getDesignResourcesList: function (params) {
      let searchData = Object.assign({ pageSize: this.pageSize, pageNo: this.pageNo }, params)
      getDesignResourcesList(searchData).then((res) => {
        if (res.code == 200) {
          this.tableData = res.data
          this.totalSize = res.totalSize
        }
      })
    },
    getTypes() {
      getLabelTypes({ type: 13 }).then((res) => {
        this.searchArr[2].data = this.getChangeDatatTypes(res.data)
      })

      getLabelTypes({ type: 14 }).then((res) => {
        this.searchArr[1].data = this.getChangeDatatTypes(res.data)
      })
    },
    projectDeptmentId(val) {
      this.projectDeptId = val
    },
    getPojectDetails(val) {
      let that = this
      let obj = {}
      let arr = []
      arr.push(val)
      obj.projectIds = arr
      obj.pageNo = 1
      obj.pageSize = 10
      getProjectBranchType(obj).then((res) => {
        if (res.code == 200 || res.data.code == 200) {
          that.form.projectType = res.data[0].designTypeName
          that.contractAmount = res.data[0].contractAmount
          this.calcChangeLevel()

          const params = {
            id: that.projectDeptId,
          }
          getDept(params).then((res) => {
            this.deptList = res.data
          })
        }
      })
    },
    bd(a, b) {
      // 求取的是区间大小值比较，因此取绝对值
      const curNum = Math.abs(Number(a.replace('%', '')))
      const rangeNum = Number(b.replace('%', ''))
      return curNum <= rangeNum
    },
    getDesignChangeLabels() {
      getDesignChangeLabels({ pageNo: 1, pageSize: 200 }).then((res) => {
        if (res.code == 200) {
          this.changeForm = res.data.changeForm // 变更形式
          // this.changeReason = res.data.changeReason // 变更原因
          // this.changeType = res.data.changeType // 变更类型
          this.profession = res.data.profession // 专业
          this.proposer = res.data.proposer // 提出方
        }
      })
    },
    getChangeReason() {
      getChangeReasons().then(res => {
        if (res.code == 200) {
          this.changeReasons = res.data
          console.log("变更原因：", res.data)
        }
      })
    },
    getChangeType(val) {
      this.changeType = []
      getChangeTypes({ value: val }).then(res => {
        if (res.code == 200) {
          this.changeType = res.data
          console.log("变更类型：", res.data)
        }
      })
    },
    getCurrentDate() {
      var d1 = new Date()
      var year = d1.getFullYear() //年
      var month = d1.getMonth() + 1 //月
      var day = d1.getDate() //日

      if (month < 10) {
        month = '0' + month
      }
      if (day < 10) {
        day = '0' + day
      }
      this.currentDate = year + '-' + month + '-' + day
    },
    searchDatas(val) {
      this.pageNo = 1
      this.getDesignResourcesList(val)
    },
    goBack() {
      if (this.type == 'approve') {
        window.close()
      } else {
        this.$router.back()
      }
    },
    saveDraft() {
      if (this.draftLoading) return


      if (this.form.branchId == null || this.form.projectId == null) {
        this.$message.error("请先选择分公司和项目！")
        return;
      }

      if (this.isEdit == 'edit') {
        this.form.id = this.id
        this.form.statusCode = 0
        if (this.form.changeReason != null && typeof (this.form.changeReason) === "string") {
          this.form.changeReason = this.form.changeReason.split(',')
        }
        this.draftLoading = true
        editDesignChange(this.form)
          .then((res) => {
            this.draftLoading = false
            if (res.data.code == 200) {
              this.$message.success('保存草稿成功！')
              this.form = {}
              this.goBack()
            }
          })
          .catch((res) => {
            this.draftLoading = false
          })
      } else {
        this.form.statusCode = 0
        if (this.form.changeReason != null) {
          this.form.changeReason = this.form.changeReason.split(',')
        }
        this.draftLoading = true
        addDesignChange(this.form)
          .then((res) => {
            this.draftLoading = false
            if (res.data?.code == 200 || res.code == 200) {
              this.$message.success('保存草稿成功！')
              this.form = {}
              this.goBack()
            }
          })
          .catch((res) => {
            this.draftLoading = false
          })
      }
    },
    /**
     *
     */
    calcChangeLevel() {
      if (this.form.changeCost == '') {
        this.form.changeRate = ''
        this.form.changeLevel = ''
      }
      if (!this.form.changeCost && this.form.changeCost !== 0 || !this.contractAmount && this.contractAmount !== 0) {
        this.form.changeLevel = ''
        return
      }
      // 单项工程设计变更率=变更费用/合同额 （%）
      let that = this
      this.form.changeRate = this.percentage(this.form.changeCost, this.contractAmount)
      // 在-5%到+5%之间为一般设计变更，除此之外为重大设计变更
      let changeSituation = that.bd(that.form.changeRate, '5%')
      if (changeSituation) {
        that.form.changeLevel = '一般设计变更'
      } else {
        that.form.changeLevel = '重大设计变更'
      }
    },

    percentage(num, total) {
      num = parseInt(num)
      total = parseInt(total)
      if (isNaN(num) || isNaN(total)) {
        return '-'
      }
      return total <= 0 ? '0%' : Math.round((num / total) * 10000) / 100.0 + '%'
    },
    submit() {
      this.setProcessConfig = null;
      this.$refs.form1.validate((err, values) => {
        if (err) {
          if (this.loading) return
          this.loading = true
          if (this.isEdit == 'edit') {
            this.form.id = this.id
            this.form.statusCode = 1
            if (this.form.changeReason != null && typeof (this.form.changeReason) === "string") {
              this.form.changeReason = this.form.changeReason.split(',')
            }
            this.submitApprovalConfirm(this.processConfig, (flag) => {
              if (!flag) {
                this.loading = false
                return
              }
              editDesignChange(this.form)
                .then((res) => {
                  this.loading = false
                  if (res?.data?.code == 200) {
                    this.$message.success('提交成功！')
                    this.form = {}
                    //提交时，返回id
                    this.businessId = this.id;
                    this.setProcessConfig = this.processConfig;
                    return
                  }
                })
                .catch((res) => {
                  this.loading = false
                })
            })

          } else {
            this.form.statusCode = 1
            if (this.form.changeReason != null) {
              this.form.changeReason = this.form.changeReason.split(',')
            }
            this.submitApprovalConfirm(this.processConfig, (flag) => {
              if (!flag) {
                this.loading = false
                return
              }
              addDesignChange(this.form)
                .then((res) => {
                  this.loading = false
                  if (res.code == 200) {
                    this.$message.success('提交成功！')
                    this.form = {}
                    //提交时，返回id
                    this.businessId = res.data;
                    this.setProcessConfig = this.processConfig;
                    return
                  }
                })
                .catch((res) => {
                  this.loading = false
                })
            })

          }
        } else {
          this.$message.warning("请填写完所有必填项信息")
        }
      })
    },
    changeData() {
      this.visible = true
      this.selectedRowKeys = []
    },
    getDesignDetails() {
      let that = this
      getDesignDetails({ id: that.id }).then((res) => {
        that.getProjectNames(that.form.branchId)
          ; (that.form.creater = JSON.parse(sessionStorage.getItem('ycloud-user_info')).name),
            (that.form.designUnitName = res.data.designUnitName)
        that.$nextTick(() => {
          that.form.projectId = res.data.projectId
        })
        that.form = { ...res.data }
        that.todoList = that.form.todoList || [];
        that.getPojectDetails(that.form.projectId)
        let _value = ""
        if (that.form.changeReason && that.form.changeReason.length > 0){
          _value = that.form.changeReason.join(',');
        }
        _value && this.getChangeType(_value)
        // _value && getChangeTypes({ value: _value }).then(res => {
        //   if (res.code == 200) {
        //     this.changeType = res.data
        //   }
       // })

        let obj = {}
        let arr = []
        arr.push(that.form.projectId)
        obj.projectIds = arr
        obj.pageNo = 1
        obj.pageSize = 10
        getProjectBranchType(obj).then((res) => {
          if (res.code == 200 || res.data.code) {
            that.contractAmount = res.data[0].contractAmount
            this.calcChangeLevel()
          }
        })
      })
    },
    getProjectNames(val) {
      let params = {}
      params.query = { branchComIds: [val], designTypeNames: ['a1类'] }
      getProject(params)
        .then((res) => {
          this.fetching = false
          if (res.code === 200) {
            this.projectNames = res.data
          } else {
            this.$message.error('err:', res.message)
          }
        })
        .catch((res) => {
          this.fetching = false
        })
    },
    onChangeTime(val) {
      this.form.changeTime = val.format('YYYY-MM-DD')
    },
    handleCancel() {
      this.visible = false
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectRow = selectedRows[0]
      this.selectedRowKeys = selectedRowKeys
    },
    handleOk() {
      this.visible = false
      this.form.designUnitName = this.selectRow.name
      this.form.designUnitId = this.selectRow.id
      this.$refs.form1.validateField('designUnitName')
    },
  },
}
</script>
